#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include <string>
using std::string;

#define MAX_LEN 4096

int init_addr(struct sockaddr_in *addr, string ip, uint16_t port)
{
    memset(addr, 0, sizeof(struct sockaddr));
    addr->sin_family = AF_INET;
    int ret = inet_pton(AF_INET, ip.c_str(), (void*)&(addr->sin_addr));
    if(ret != 1){
        printf("get network byte order binary address failed.\n");
        return -1;
    } else {
        printf("inet_pton ip address: 0x%x\n", (addr->sin_addr).s_addr);
    }

    addr->sin_port = htons(port);
    return 0;
}

int main()
{
    int socket_fd;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd == -1) {
        printf("creat socket failed.\n");
        return -1;
    }

    struct sockaddr_in addr;
    int ret = init_addr(&addr, "10.1.1.131", 6666);
    if(ret < 0) {
        return -1;
    }

	printf("socket_fd = %d\n", socket_fd);

    //connect
    ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0) {
        printf("connect to service failed, errno:%d\n", errno);
        return -1;
    }

	printf("get connect succeed, ret = %d\n", ret);

    //send and recv;
    string str = "hello world!";
    int n = send(socket_fd, str.c_str(), str.size() +1, 0); 
    if(n < 0) {
        printf("send msg failed, drrno:%d\n", errno);
        return -1;
    }else {
        printf("send msg succeed, msg size:%d\n", n);
    }

	char buf[1024] = {0};
	n =  recv(socket_fd, buf, sizeof(buf), 0);
	if(n < 0) {
		printf("recv msg failed, errno:%d\n", errno);
		return -1;
	}

	printf("Get resule:%s\n", buf);
    return 0;
}
